<template>
  <div class="echart-line-container">
    <div
      ref="chart"
      style="width: 100%; height: 100%"
    ></div>
    <div
      class="echart-line-compnent"
      ref="select"
    >
      <el-select
        collapse-tags
        class="echart-device-select"
        :popper-append-to-body="false"
        size="mini"
        placeholder="设备名称"
        v-model="uuidList"
        filterable
        reserve-keyword
        remote
        :remote-method="remoteSearch"
        :loading="remoteLoading"
        clearable
        @change="selectChange"
      >
        <el-option
          v-for="item in itemList"
          :key="item.uuid"
          :value="item.uuid"
          :label="item.name"
        ></el-option>
      </el-select>
      <div class="picker-component">
        <el-date-picker
          popper-class="echart-data"
          class="echart-device-history-time"
          style="width: 200px"
          size="mini"
          prefix-icon="icon-remove"
          clear-icon="icon-remove"
          v-model="modulePickTime"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :picker-options="pickerOptions"
          @change="logTime"
        ></el-date-picker>
      </div>
    </div>
  </div>
</template>

<script>
import { queryDeviceListApi } from '../../../api/device';
import { Message, MessageBox } from 'element-ui';
import echarts from 'echarts';
import { parseError } from '../../../utils';
export default {
  props: {
    dataSetSource: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      showChart: false,
      itemList: [],
      uuidList: '',
      modulePickTime: '',
      start: '',
      end: '',
      remoteLoading: false,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一天',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }
          // {
          //   text: '最近一年',
          //   onClick(picker) {
          //     const end = new Date();
          //     const start = new Date();
          //     start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
          //     picker.$emit('pick', [start, end]);
          //   }
          // }
        ]
      }
    };
  },
  mounted() {
    // this.getEchartData();
    // this.remoteSearch();
    // this.defaultView();
    this.defaultShow();
    window.addEventListener('resize', this.onResize);
  },
  methods: {
    selectChange(value) {
      if (value && this.modulePickTime) {
        this.$emit('getData', this.uuidList, this.start, this.end);
      }
    },
    async defaultShow() {
      await this.remoteSearch();
      if (this.itemList.length !== 0) {
        this.uuidList = this.itemList[0].uuid;
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24);
        this.start = start;
        this.end = end;
        this.modulePickTime = [this.start, this.end];
        this.$emit('getData', this.uuidList, this.start, this.end);
      }
    },
    remoteSearch(name) {
      return new Promise((resolve, reject) => {
        this.remoteLoading = true;
        queryDeviceListApi(name, 5)
          .then(res => {
            this.itemList = res;
            resolve();
          })
          .catch(error => {
            Message.error(parseError(error));
            reject(error);
          })
          .finally(() => (this.remoteLoading = false));
      });
    },
    transformTime(value) {
      const d = new Date(value);
      const datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
      return moment(datetime).utc().format();
    },
    logTime() {
      if (this.uuidList.length == 0) {
        this.modulePickTime = [];
        return Message.warning('请先选择设备');
      }
      this.start = this.transformTime(this.modulePickTime[0]);
      this.end = this.transformTime(this.modulePickTime[1]);
      this.$emit('getData', this.uuidList, this.start, this.end);
    },
    onResize() {
      this.myChart.resize();
      this.myChart.setOption({
        grid: { top: this.$refs.select.clientHeight > 60 ? this.$refs.select.clientHeight : 60 }
      });
    },
    getEchartData() {
      const chart = this.$refs.chart;
      this.myChart = echarts.init(chart);
      if (chart) {
        const option = {
          title: {
            text: '设备数据曲线',
            top: '10px',
            left: '10px',
            textStyle: {
              color: '#636985'
            }
          },
          grid: { top: this.$refs.select.clientHeight > 60 ? this.$refs.select.clientHeight : 60 },
          legend: {
            bottom: 0,
            textStyle: {
              color: '#66769b'
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              label: {
                backgroundColor: '#6a7985'
              }
            }
          },
          // dataset: {
          //   source: this.dataSetSource
          // },
          xAxis: {
            type: 'time',
            nameTextStyle: { color: '#000' },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#000'
              }
            },
            axisLine: {
              lineStyle: {
                color: '#000'
              }
            },
            splitLine: {
              show: false
            }
          },
          yAxis: {
            gridIndex: 0,
            name: this.dataSetSource.length !== 0 ? this.dataSetSource[0].parameter_unit : '',
            nameGap: 10,
            nameTextStyle: { color: '#000' },
            axisLine: {
              lineStyle: {
                color: '#000'
              }
            },
            axisLabel: {
              show: true,
              textStyle: {
                color: '#000'
              }
            },
            splitLine: {
              show: false
            }
          },
          series: this.dataSetSource.map(line => {
            return {
              symbol: 'none',
              name: line.device_name,
              type: 'line',
              data: line.data.map(item => [item.created_at, item.value]),
              smooth: true,
              legend: {
                show: true
              },
              label: {
                show: false,
                color: '#fff'
              }
            };
          })
        };
        this.myChart.setOption(option, true);
      }
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.onResize);
  }
};
</script>

<style lang="scss" scoped>
.echart-line-container {
  position: relative;
  .echart-line-compnent {
    position: absolute;
    top: 0;
    right: 0;
    width: 75%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
  }
  .picker-component {
    padding: 10px 10px 0 0;
  }
  .echart-device-select {
    padding: 10px 10px 0 0;
    // position: absolute;
    // top: 5px;
    // right: 15vw;
    width: 150px;
    /deep/.el-select-dropdown {
      border: 0;
    }
  }
}
</style>

<style lang="scss">
.echart-device-history-time {
  // padding: 5px 5px 0 0 !important;
  // margin-left: 10px;
  /deep/.el-input__icon {
    display: none !important;
  }
}
.icon-remove {
  display: none;
}
</style>
